import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import * as geoip from 'geoip-lite';

@Injectable()
export class WeatherService {
  constructor(private readonly configService: ConfigService) {}
  async getExternalIP() {
    try {
      const ipApiUrl = this.configService.get('IP_API_URL');

      const res = await axios.get(ipApiUrl);
      return res.data.ip;
    } catch (error) {
      console.log(`ip出错`, error);
      return 'N/A';
    }
  }
  async getWeather() {
    const ip = await this.getExternalIP();
    const geo = geoip.lookup(ip);
    const location = geo ? `${geo.city},${geo.country}` : 'Unknown';
    let werther = '无法获取当地的天气信息';
    console.log(ip, location);
    try {
      const weatherApiUrl = this.configService.get('WEATHER_API_URL');
      const weatherApiKey = this.configService.get('WEATHER_API_KEY');
      const response = await axios.get(
        `${weatherApiUrl}?lang=zh&key=${weatherApiKey}&q=${location}`,
      );
      werther = `${response.data.current.temp_c}度,${response.data.current.condition.text}`;
    } catch (error) {
      console.log('获取天气信息失败', error.message);
      throw new InternalServerErrorException('获取天气信息失败');
    }
    return werther;
  }
}
